package com.web.gatewayservice.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;




/**
 * @author lenovo
 * @Description
 * @Date2025/4/21 下午5:11
 */

@Order(-1)
@Component
public class MyGlobalExceptionHandler implements ErrorWebExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(MyGlobalExceptionHandler.class);

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        if (response.isCommitted()){
            return Mono.error(ex);
        }
        String msg="";
        if (ex instanceof NotFoundException){
            msg="你的服务不见了";
        }else if (ex instanceof ResponseStatusException){
            msg="响应出现问题";
        }else {
            msg="服务器出现问题";
        }
        logger.debug("服务器异常处理：{}",msg);
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON.toString());
        DataBuffer dataBuffer=response.bufferFactory().wrap(msg.getBytes());
        return response.writeWith(Mono.just(dataBuffer));

    }
}
